package com.mdp.tpa.pay.paypal.service;

import com.mdp.tpa.pay.paypal.entity.PaypalPaymentIntent;
import com.mdp.tpa.pay.paypal.entity.PaypalPaymentMethod;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 支付service类
 */
@Service
public class PaypalService {
    // 注入凭证信息bean
    @Autowired
    private APIContext apiContext;

    /**
     * 创建支付订单
     * @param total  交易金额
     * @param currency 货币类型
     * @param method  付款类型
     * @param intent  收款方式
     * @param description  交易描述
     * @param cancelUrl  取消后回调地址
     * @param successUrl  成功后回调地址
     */
    public Payment createPayment(
            String orderId,
            Double total,
            String currency,
            PaypalPaymentMethod method,
            PaypalPaymentIntent intent,
            String description,
            String cancelUrl,
            String successUrl) throws PayPalRESTException {
        // 设置金额和单位对象
        Amount amount = new Amount();
        amount.setCurrency(currency);
        amount.setTotal(String.format("%.2f", total));
        // 设置具体的交易对象
        Transaction transaction = new Transaction();
        transaction.setDescription(description);
        transaction.setAmount(amount);
        transaction.setCustom(orderId);
        // 交易集合-可以添加多个交易对象
        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        Payer payer = new Payer();
        payer.setPaymentMethod(method.toString());//设置交易方式

        Payment payment = new Payment();
        payment.setIntent(intent.toString());//设置意图
        payment.setPayer(payer);
        payment.setTransactions(transactions);
        // 设置反馈url
        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setCancelUrl(cancelUrl);
        redirectUrls.setReturnUrl(successUrl);
        // 加入反馈对象
        payment.setRedirectUrls(redirectUrls);
        // 加入认证并创建交易
        return payment.create(apiContext);
    }

    /**
     * 执行支付
     *   获取支付订单，和买家ID，执行支付
     */
    public Payment executePayment(String paymentId, String payerId) throws PayPalRESTException{
        Payment payment = new Payment();
        payment.setId(paymentId);
        PaymentExecution paymentExecute = new PaymentExecution();
        paymentExecute.setPayerId(payerId);
        return payment.execute(apiContext, paymentExecute);
    }
}